package base.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import java.io.*
import java.text.SimpleDateFormat
import java.util.*


/**
 * Created by Jack on 2017/10/23.
 */
object CompressImageUtil {

    fun saveBitmapFile(bitmap: Bitmap): File {
        val format = SimpleDateFormat("yyyyMMddHHmmss")
        val fileName = format.format(Date()) + ".png"
        val myDir = File(Environment.getExternalStorageDirectory(), "EZG/temporary/images")
        if (!myDir.exists()) {
            myDir.mkdirs()
        }
        val file = File(myDir, fileName)
        if (file.exists()) {
            file.delete()
        }
        try {
            val bos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return file
    }

    fun saveBitmapFile(bitmap: Bitmap, quality: Int): File {
        val format = SimpleDateFormat("yyyyMMddHHmmss")
        val fileName = format.format(Date()) + ".png"
        val myDir = File(Environment.getExternalStorageDirectory(), "EZG/temporary/images")
        if (!myDir.exists()) {
            myDir.mkdirs()
        }
        val file = File(myDir, fileName)
        if (file.exists()) {
            file.delete()
        }
        try {
            val bos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return file
    }

    fun saveBitmapFile(filePath: String): File {
        val format = SimpleDateFormat("yyyyMMddHHmmss")
        val fileName = format.format(Date()) + ".jpg"
        val myDir = File(Environment.getExternalStorageDirectory(), "EZG/temporary/images")
        if (!myDir.exists()) {
            myDir.mkdirs()
        }
        val file = File(myDir, fileName)
        if (file.exists()) {
            file.delete()
        }
        val bitmap = BitmapFactory.decodeFile(filePath, getBitmapOption(2))
        try {
            val bos = BufferedOutputStream(FileOutputStream(file))
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return file
    }

    fun getBitMap(path: String, reqWidth: Int, reqHeight: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(path, options)
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
        options.inJustDecodeBounds = false
        val src = BitmapFactory.decodeFile(path, options)
        return createScaleBitmap(src, reqWidth, reqHeight)
    }

    private fun getBitmapOption(inSampleSize: Int): BitmapFactory.Options {
        System.gc()
        val options = BitmapFactory.Options()
        options.inPurgeable = true
        options.inSampleSize = inSampleSize
        return options
    }

    private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        val height = options.outHeight
        val width = options.outWidth
        var inSampleSize = 1
        if (height > reqHeight || width > reqWidth) {
            val halfHeight = height / 2
            val halfWidth = width / 2
            while (halfHeight / inSampleSize > reqHeight && halfWidth / inSampleSize > reqWidth) {
                inSampleSize *= 2
            }
        }
        return inSampleSize
    }

    // 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响
    private fun createScaleBitmap(src: Bitmap, dstWidth: Int,
                                  dstHeight: Int): Bitmap {
        val dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false)
        if (src != dst) { // 如果没有缩放，那么不回收
            src.recycle() // 释放Bitmap的native像素数组
        }
        return dst
    }


    fun compressImage(image: Bitmap, quality: Int): File? {
        val format = SimpleDateFormat("yyyyMMddHHmmssSSSS")
        val fileName = format.format(Date()) + ".jpg"
        val myDir = File(Environment.getExternalStorageDirectory(), "EZG/temporary/images")
        if (!myDir.exists()) {
            myDir.mkdirs()
        }
        val file = File(myDir, fileName)
        if (file.exists()) {
            file.delete()
        }
        try {
            val os = ByteArrayOutputStream()
            image.compress(Bitmap.CompressFormat.JPEG, quality, os)
            val fos = FileOutputStream(file.absolutePath)
            fos.write(os.toByteArray())
            fos.flush()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }

        return file
    }
}
